import 'package:get/get.dart';
import 'package:get_storage/get_storage.dart';
import 'package:flutter/foundation.dart';
import '../models/user_model.dart';
import '../repositories/system_repository.dart';

class UserService extends GetxService {
  final _box = GetStorage();
  static const String _userInfoKey = 'user_info';

  // 用户信息响应式状态
  final Rx<UserInfo?> _userInfo = Rx<UserInfo?>(null);
  final RxList<String> roles = <String>[].obs;
  final RxList<String> permissions = <String>[].obs;

  // 系统仓库
  final SystemRepository _systemRepository = Get.find<SystemRepository>();

  // 获取实例的便捷方法
  static UserService get to => Get.find<UserService>();

  // 初始化
  Future<UserService> init() async {
    // 尝试从本地存储加载用户信息
    _loadUserInfoFromStorage();
    return this;
  }

  // 从本地存储加载用户信息
  void _loadUserInfoFromStorage() {
    try {
      final dynamic userData = _box.read(_userInfoKey);
      if (userData != null && userData is Map<String, dynamic>) {
        UserInfoResponse userInfoResponse = UserInfoResponse.fromJson(userData);
        _updateUserState(userInfoResponse);
      }
    } catch (e) {
      // 如果读取失败，清除用户信息
      clearUserInfo();
    }
  }

  // 保存用户信息到本地存储
  void _saveUserInfoToStorage(UserInfoResponse userInfo) {
    try {
      Map<String, dynamic> userData = {
        'user': {
          'userId': userInfo.user.userId,
          'userName': userInfo.user.userName,
          'nickName': userInfo.user.nickName,
          'deptId': userInfo.user.deptId,
          'email': userInfo.user.email,
          'phonenumber': userInfo.user.phonenumber,
          'sex': userInfo.user.sex,
          'avatar': userInfo.user.avatar,
          'status': userInfo.user.status,
        },
        'roles': userInfo.roles,
        'permissions': userInfo.permissions,
      };
      _box.write(_userInfoKey, userData);
    } catch (e) {
      // 写入失败时的错误处理
      debugPrint('保存用户信息失败: $e');
    }
  }

  // 更新用户状态
  void _updateUserState(UserInfoResponse userInfo) {
    _userInfo.value = userInfo.user;
    roles.assignAll(userInfo.roles);
    permissions.assignAll(userInfo.permissions);
  }

  // 获取用户信息
  Future<UserInfo?> getUserInfo() async {
    try {
      UserInfoResponse userInfo = await _systemRepository.getUserInfo();
      _updateUserState(userInfo);
      _saveUserInfoToStorage(userInfo);
      return userInfo.user;
    } catch (e) {
      rethrow;
    }
  }

  // 清除用户信息
  void clearUserInfo() {
    _box.remove(_userInfoKey);
    _userInfo.value = null;
    roles.clear();
    permissions.clear();
  }

  // 检查是否有指定权限
  bool hasPermission(String permission) {
    // 如果有管理员角色或通配符权限，直接返回true
    if (roles.contains('admin') || permissions.contains('*:*:*')) {
      return true;
    }

    return permissions.contains(permission);
  }

  // 检查是否有指定角色
  bool hasRole(String role) {
    return roles.contains(role);
  }

  // 获取用户名称
  String get userName => _userInfo.value?.userName ?? '';

  // 获取用户昵称
  String get nickName => _userInfo.value?.nickName ?? '';

  // 获取用户头像
  String get avatar => _userInfo.value?.avatar ?? '';

  // 获取当前用户信息
  UserInfo? get currentUser => _userInfo.value;

  // 设置当前用户信息
  set currentUser(UserInfo? user) => _userInfo.value = user;

  // 获取响应式用户对象
  Rx<UserInfo?> get currentUserRx => _userInfo;

  /// 用户是否已登录
  bool get isLoggedIn => _userInfo.value != null;

  /// 检查用户是否拥有指定角色之一
  bool hasAnyRole(List<String> roleList) {
    if (_userInfo.value == null) {
      return false;
    }

    return roleList.any((role) => roles.contains(role));
  }
}
